package com.qf.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.constant.RabbitConstant;
import com.qf.constant.RedisConstant;
import com.qf.dto.EmailMessageDTO;
import com.qf.dto.ResultBean;
import com.qf.entity.TUser;
import com.qf.mapper.TUserMapper;
import com.qf.service.IUserService;
import com.qf.util.StringUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by IntelliJ IDEA.
 * User: dong
 * Date: 2020/3/12
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private TUserMapper mapper;

    @Value("${activeAccountServer}")
    String activeAccountServer;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public List<TUser> getAll() {
        return mapper.selectAll();
    }

    //邮箱注册
    @Override
    public ResultBean registerByEmail(String email, String password) {

        try {
            //1、发邮件
            EmailMessageDTO message = new EmailMessageDTO();
            message.setEmail(email);
            //生成uuid
            String uuid = UUID.randomUUID().toString();
            //创建url
            String url  = activeAccountServer+uuid;
            message.setUrl(url);
            rabbitTemplate.convertAndSend(RabbitConstant.EMAIL_TOPIC_EXCHANGE,"email.register",message);

            //2、将数据插入到数据库
            TUser user = new TUser();
            user.setEmail(email);
            //加密存入
//            user.setPassword(SpringSecurityUtil.getEncondepassword(password));
            //正常存入
            user.setPassword(password);
            mapper.insertSelective(user);
            //3、存入到redis中
            //组织键
            String redisKey = StringUtil.getRedisKey(RedisConstant.REGISTER_EMAIL,uuid);
            redisTemplate.opsForValue().set(redisKey,email,10, TimeUnit.MINUTES);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("注册失败");
        }
        return ResultBean.success("注册成功");
    }

    //邮箱激活
    @Override
    public ResultBean emailActive(String email) {
        TUser user = new TUser();
        user.setEmail(email);
        int las = email.lastIndexOf("@");
        String uname = email.substring(0,las);
        user.setUname(uname);
        user.setFlag(true);
        Example example = new Example(TUser.class);
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("email",email);
        mapper.updateByExampleSelective(user,example);
        return ResultBean.success("激活成功");
    }

    //发送短信验证码
    @Override
    public ResultBean getCode(String phone) {
        rabbitTemplate.convertAndSend(RabbitConstant.SMS_TOPIC_EXCHANGE,"sms.send",phone);
        return ResultBean.success();
    }

    //手机号注册
    @Override
    public ResultBean registerByPhone(String phone, String code, String password) {
        //1、校验验证码
        String redisKey = StringUtil.getRedisKey(RedisConstant.REGISTER_PHONE,phone);
        String redisCode = (String)redisTemplate.opsForValue().get(redisKey);
        if (code.equals(redisCode)){
            //验证码正确
            TUser user = new TUser();
            user.setPassword(password);
            user.setPhone(phone);
            user.setUname(phone);
            user.setFlag(true);
            //插入到数据库中
            mapper.insertSelective(user);
            return ResultBean.success("注册成功");
        }
        return ResultBean.error("验证码错误");
    }

    //登录校验
    @Override
    public ResultBean checkLogin(String uname, String password) {
        Example example = new Example(TUser.class);
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("uname",uname);
        TUser user = mapper.selectOneByExample(example);
        if (user!=null){
            if (password!=null&&password.equals(user.getPassword())){
                //登录成功
                ResultBean resultBean = ResultBean.success(user, "登录成功");
                return resultBean;
            }
        }
        return ResultBean.error("账号或密码错误");
    }

    /**
     * 根据uuid组织键，去redis查询有没有对应的uuid
     * @param uuid
     * @return
     */
    @Override
    public ResultBean checkIsLogin(String uuid) {
        if (uuid!=null&&!"".equals(uuid)){
            //1、组织键
            String redisKey = StringUtil.getRedisKey(RedisConstant.USER_LOGIN_PRE,uuid);
            //2、去redis中查询
            Object o = redisTemplate.opsForValue().get(redisKey);
            if (o!=null){
                TUser user = (TUser) o;
                user.setPassword("");
                return ResultBean.success(user,"用户已登录");
            }
        }
        return ResultBean.error("用户未登录");
    }


}
